package com.zz.ecommerce.mybatis.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用于完成从null值到空串的转换的TypeHandler
 *
 * @author rocky
 * @date 2015/8/13,11:24
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String.class)
public class EmptyStringIfNullHandler implements TypeHandler<String> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void setParameter(final PreparedStatement ps, final int i, final String parameter, final JdbcType jdbcType)
        throws SQLException {

    }

    @Override
    public String getResult(final ResultSet rs, final String columnName) throws SQLException {
//        logger.debug("rs.getString(" + columnName + ")=" + rs.getString(columnName));
        return (rs.getString(columnName) == null) ? "" : rs.getString(columnName);
    }

    @Override
    public String getResult(final ResultSet rs, final int columnIndex) throws SQLException {
//        logger.debug("rs.getString(" + columnIndex + ")=" + rs.getString(columnIndex));
        return (rs.getString(columnIndex) == null) ? "" : rs.getString(columnIndex);
    }

    @Override
    public String getResult(final CallableStatement cs, final int columnIndex) throws SQLException {
//        logger.debug("cs.getString(" + columnIndex + ")=" + cs.getString(columnIndex));
        return (cs.getString(columnIndex) == null) ? "" : cs.getString(columnIndex);
    }
}
